<template>
  <div class="teacher-grade-entry">
    <h2>成绩录入</h2>
    <el-card shadow="never" class="filter-card">
      <el-form :inline="true" :model="query" size="small">
        <el-form-item label="课程名">
          <el-input v-model="query.courseName" placeholder="输入课程名称关键字"></el-input>
        </el-form-item>
        <el-form-item label="学生名">
          <el-input v-model="query.studentName" placeholder="输入学生姓名关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchData(1)">查询</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card shadow="never" class="table-card">
      <el-table :data="records" v-loading="loading" size="small" style="width: 100%; min-width: 900px; table-layout: fixed;" :show-header="true" :border="false">
        <el-table-column prop="id" label="选课ID" min-width="100" align="center" />
        <el-table-column prop="courseName" label="课程名" min-width="180" align="center" />
        <el-table-column prop="studentName" label="学生姓名" min-width="140" align="center" />
        <el-table-column prop="dailyScore" label="日常分" min-width="140" align="center">
          <template slot-scope="{ row }">
            <el-input-number v-model="row.editDaily" :min="0" :max="100" size="mini" style="width:90px;" />
          </template>
        </el-table-column>
        <el-table-column prop="examScore" label="笔试分" min-width="140" align="center">
          <template slot-scope="{ row }">
            <el-input-number v-model="row.editExam" :min="0" :max="100" size="mini" style="width:90px;" />
          </template>
        </el-table-column>
        <el-table-column label="成绩" min-width="120" align="center">
          <template slot-scope="{ row }">
            {{ computeTotal(row) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="120" align="center" fixed="right">
          <template slot-scope="{ row }">
            <el-button type="primary" size="mini" @click="saveRow(row)" :loading="row._saving">打分</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pager">
        <el-pagination
          background
          layout="prev, pager, next, jumper, ->, total"
          :page-size="pageSize"
          :current-page.sync="page"
          @current-change="fetchData"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>
<script>
import { getGradePage, getGradePageCount, saveGrade } from '@/api'
export default {
  name:'TeacherGradeEntry',
  data(){ return { query:{ courseName:'', studentName:'' }, loading:false, records:[], page:1, pageSize:10, total:0, teacherName:'', tableHeight: '540px' } },
  created(){
    const info = this.$store.state.user.userInfo || JSON.parse(localStorage.getItem('userInfo')||'{}')
    this.teacherName = info.username || info.name || ''
    this.fetchData(1)
  },
  methods:{
    async fetchData(p){ if(p) this.page=p; this.loading=true; try {
  const params = { ...this.query, teacherName:this.teacherName }
      const countRes = await getGradePageCount(params)
      // countRes.data 可能返回页数或总条数，这里假设是总条数; 如果是页数则乘以 pageSize
      let total = countRes.data || 0
      if (total && total < 50 && total < this.page) { // 简单容错
        total = total * this.pageSize
      }
      this.total = total
      const listRes = await getGradePage(this.page, params)
      this.records = (listRes.data || []).map(r=>({ ...r, editDaily:r.dailyScore, editExam:r.examScore }))
    } catch(e){ this.$message.error('加载数据失败') } finally { this.loading=false } },
  reset(){ this.query.courseName=''; this.query.studentName=''; this.fetchData(1) },
    computeTotal(row){ const d = row.editDaily!=null?row.editDaily:0; const e = row.editExam!=null?row.editExam:0; return Math.round(d*0.4 + e*0.6) },
    async saveRow(row){
      row._saving=true;
      try {
        // 构造尽可能完整的 payload，兼容后端可能要求的字段
        const total = this.computeTotal(row)
        const payloadRaw = {
          id: row.id,
          dailyScore: row.editDaily,
          examScore: row.editExam,
          score: total, // 总成绩
          courseId: row.courseId || row.courseID || row.cid,
          studentId: row.studentId || row.studentID || row.sid,
          studentCourseId: row.studentCourseId || row.selectionId || row.selectId
        }
        // 移除 undefined / null
        const payload = {}
        Object.keys(payloadRaw).forEach(k=>{
          const v = payloadRaw[k]
            if (v !== undefined && v !== null && v !== '') payload[k]=v
        })
        if (process.env.NODE_ENV !== 'production') {
          console.debug('[GradeEntry][saveRow][row]', JSON.parse(JSON.stringify(row)))
          console.debug('[GradeEntry][saveRow][payload]', payload)
        }
        let success = false
        try {
          await saveGrade(payload)
          success = true
        } catch(err) {
          // 如果 PUT 400，尝试使用 POST 兼容一次（部分后端可能用 POST 更新）
          const status = err?.response?.status
          if (status === 400) {
            if (process.env.NODE_ENV !== 'production') console.warn('[GradeEntry][saveRow] PUT 400, try POST fallback')
            try {
              await this.$axios({ // 直接使用底层 axios（已在 Vue 原型链? 若无则跳过）
                url: '/api/teacher/grade',
                method: 'post',
                data: payload
              })
              success = true
            } catch(postErr) {
              throw postErr
            }
          } else {
            throw err
          }
        }
        if (success) {
          row.dailyScore = row.editDaily; row.examScore=row.editExam; row.score = total
          this.$message.success('保存成功')
        }
      } catch(e){
        const msg = e?.response?.data?.message
        if (process.env.NODE_ENV !== 'production') {
          console.error('[GradeEntry][saveRow][error]', e?.response || e)
        }
        this.$message.error('保存失败' + (msg?(': '+msg):''))
      } finally { row._saving=false }
    }
  }
}
</script>
<style scoped>
.teacher-grade-entry { padding:16px; }
.filter-card { margin-bottom:12px; }
.table-card { padding:0; }
.teacher-grade-entry ::v-deep(.el-form-item) { margin-right:12px; }
.teacher-grade-entry ::v-deep(.el-table) { font-size:13px; background:transparent; }
.teacher-grade-entry ::v-deep(.el-table th),
.teacher-grade-entry ::v-deep(.el-table td) {
  padding: 10px 12px;
  text-align: center;
  border: none !important;
}
.teacher-grade-entry ::v-deep(.el-table__body-wrapper) { background:transparent; }
.teacher-grade-entry ::v-deep(.el-table__row) { background:transparent; }
.teacher-grade-entry ::v-deep(.el-table__empty-block) { background:transparent; }
.teacher-grade-entry ::v-deep(.el-table__fixed-right) { background:transparent; }
.pager { margin-top:8px; text-align:right; }
</style>
